package com.employment.service.impl;

import com.employment.dao.ResumeMapper;
import com.employment.entity.Resume;
import com.employment.service.ResumeService;
import com.mybatisflex.core.paginate.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 简历管理服务实现类
 * 
 * @author Employment System
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ResumeServiceImpl implements ResumeService {

    private final ResumeMapper resumeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createResume(Resume resume) {
        try {
            // 设置初始值
            resume.setViewCount(0);
            resume.setDownloadCount(0);
            resume.setIsDefault(0);
            resume.setIsPublic(1);
            resume.setStatus(1);
            
            // 计算完整度
            Integer completeness = calculateCompleteness(resume);
            resume.setCompleteness(completeness);
            
            boolean success = resumeMapper.insert(resume) > 0;
            
            // 如果是用户第一份简历，设置为默认简历
            if (success) {
                List<Resume> userResumes = resumeMapper.selectByUserId(resume.getUserId());
                if (userResumes.size() == 1) {
                    setDefaultResume(resume.getResumeId(), resume.getUserId());
                }
            }
            
            return success;
        } catch (Exception e) {
            log.error("创建简历失败: ", e);
            throw new RuntimeException("创建简历失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateResume(Resume resume) {
        try {
            // 计算完整度
            Integer completeness = calculateCompleteness(resume);
            resume.setCompleteness(completeness);
            
            return resumeMapper.update(resume) > 0;
        } catch (Exception e) {
            log.error("更新简历失败: ", e);
            throw new RuntimeException("更新简历失败");
        }
    }

    @Override
    public boolean deleteResume(Long resumeId) {
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteResume(Long resumeId, Long userId) {
        try {
            // 检查简历是否属于当前用户
            Resume resume = resumeMapper.selectOneById(resumeId);
            if (resume == null || !resume.getUserId().equals(userId)) {
                throw new RuntimeException("简历不存在或无权限删除");
            }
            
            // 如果删除的是默认简历，需要设置其他简历为默认
            if (resume.getIsDefault() == 1) {
                List<Resume> userResumes = resumeMapper.selectByUserId(userId);
                if (userResumes.size() > 1) {
                    for (Resume r : userResumes) {
                        if (!r.getResumeId().equals(resumeId)) {
                            setDefaultResume(r.getResumeId(), userId);
                            break;
                        }
                    }
                }
            }
            
            return resumeMapper.deleteById(resumeId) > 0;
        } catch (Exception e) {
            log.error("删除简历失败: ", e);
            throw new RuntimeException("删除简历失败");
        }
    }

    @Override
    public Resume getResumeById(Long resumeId) {
        return resumeMapper.selectOneById(resumeId);
    }

    @Override
    public List<Resume> getResumesByUserId(Long userId) {
        return resumeMapper.selectByUserId(userId);
    }

    @Override
    public Resume getDefaultResumeByUserId(Long userId) {
        return resumeMapper.selectDefaultByUserId(userId);
    }

    @Override
    public Page<Resume> getPublicResumePage(Page<Resume> page,
                                             String keyword,
                                             String city,
                                             String position,
                                             String industry,
                                             Integer jobStatus) {
        return resumeMapper.selectPublicResumePage(page, keyword, city, position, industry, jobStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefaultResume(Long resumeId, Long userId) {
        try {
            return resumeMapper.setDefaultResume(userId, resumeId) > 0;
        } catch (Exception e) {
            log.error("设置默认简历失败: ", e);
            throw new RuntimeException("设置默认简历失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean increaseViewCount(Long resumeId) {
        try {
            return resumeMapper.increaseViewCount(resumeId) > 0;
        } catch (Exception e) {
            log.error("增加浏览次数失败: ", e);
            return false;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean increaseDownloadCount(Long resumeId) {
        try {
            return resumeMapper.increaseDownloadCount(resumeId) > 0;
        } catch (Exception e) {
            log.error("增加下载次数失败: ", e);
            return false;
        }
    }

    @Override
    public List<Resume> searchResumes(String keyword, Integer limit) {
        return resumeMapper.searchResumes(keyword, limit);
    }

    @Override
    public Integer calculateCompleteness(Resume resume) {
        int totalFields = 15; // 总字段数
        int filledFields = 0;
        
        // 检查必填字段
        if (StringUtils.hasText(resume.getName())) filledFields++;
        if (StringUtils.hasText(resume.getPhone())) filledFields++;
        if (StringUtils.hasText(resume.getEmail())) filledFields++;
        
        // 检查可选字段
        if (resume.getGender() != null) filledFields++;
        if (resume.getBirthDate() != null) filledFields++;
        if (StringUtils.hasText(resume.getCurrentCity())) filledFields++;
        if (StringUtils.hasText(resume.getExpectedPosition())) filledFields++;
        if (StringUtils.hasText(resume.getExpectedCity())) filledFields++;
        if (resume.getExpectedSalaryMin() != null) filledFields++;
        if (resume.getExpectedSalaryMax() != null) filledFields++;
        if (StringUtils.hasText(resume.getSelfIntroduction())) filledFields++;
        if (StringUtils.hasText(resume.getSkills())) filledFields++;
        if (StringUtils.hasText(resume.getAdvantages())) filledFields++;
        if (StringUtils.hasText(resume.getAvatar())) filledFields++;
        if (resume.getJobStatus() != null) filledFields++;
        
        return (int) ((double) filledFields / totalFields * 100);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCompleteness(Long resumeId) {
        try {
            Resume resume = resumeMapper.selectOneById(resumeId);
            if (resume == null) {
                return false;
            }
            
            Integer completeness = calculateCompleteness(resume);
            resume.setCompleteness(completeness);
            
            return resumeMapper.update(resume) > 0;
        } catch (Exception e) {
            log.error("更新简历完整度失败: ", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Resume copyResume(Long resumeId, Long userId) {
        try {
            Resume sourceResume = resumeMapper.selectOneById(resumeId);
            if (sourceResume == null) {
                throw new RuntimeException("源简历不存在");
            }
            
            Resume newResume = new Resume();
            BeanUtils.copyProperties(sourceResume, newResume);
            
            // 清除原有ID和设置新的属性
            newResume.setResumeId(null);
            newResume.setUserId(userId);
            newResume.setTitle(sourceResume.getTitle() + " - 副本");
            newResume.setIsDefault(0);
            newResume.setViewCount(0);
            newResume.setDownloadCount(0);
            
            boolean success = resumeMapper.insert(newResume) > 0;
            if (success) {
                return newResume;
            }
            
            throw new RuntimeException("复制简历失败");
        } catch (Exception e) {
            log.error("复制简历失败: ", e);
            throw new RuntimeException("复制简历失败");
        }
    }

    @Override
    public String exportResume(Long resumeId, String format) {
        // TODO: 实现简历导出功能
        // 这里可以集成Apache POI或其他文档生成库
        log.info("导出简历: resumeId={}, format={}", resumeId, format);
        return "/exports/resume_" + resumeId + "." + format;
    }
}